package com.tsystems.clientEmployee.gui;

import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.tsysstems.clientEmployee.ClientEmployee;
import com.tsystems.entities.TimeTableElement;

public class TTEManagementPanel extends JPanel {

	TimeTableElementTable timeTableElementsTable = new TimeTableElementTable();
	private static final long serialVersionUID = 6489712085149821505L;

	Logger logger = LoggerFactory.getLogger(getClass());

	public TTEManagementPanel() {
		super(new GridBagLayout());

		setBorder(new TitledBorder("Расписание"));

		timeTableElementsTable.updateTable(ClientEmployee.getInstance()
				.viewTimeTableElements());
		timeTableElementsTable.setSelectListener(new ListSelectionListener() {

			public void valueChanged(ListSelectionEvent e) {

			}
		});

		add(new JScrollPane(timeTableElementsTable), new GridBagConstraints(0,
				0, 1, 1, 1.0, 1.0, GridBagConstraints.CENTER,
				GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0));
		add(createButtonPanel(), new GridBagConstraints(0, 1, 1, 1, 1.0, 0.0,
				GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL,
				new Insets(-5, 0, 0, 0), 0, 0));

	}

	public JPanel createButtonPanel() {

		JPanel result = new JPanel(new FlowLayout());
		JButton addTrain = new JButton("Добавить элемент расписания");
		addTrain.addActionListener(new ActionListener() {

			public void actionPerformed(ActionEvent e) {
				TimeTableElement timeTableElement = AddTTEPanel
						.showDialog(JOptionPane.getRootFrame());
				if(timeTableElement==null){
					return;
				}
				String result =ClientEmployee.getInstance().addTTE(timeTableElement);
				if(result==null){
					JOptionPane
					.showMessageDialog(TTEManagementPanel.this,
							"Произошла внутренняя ошибка приложения, обратитесь к администратору!");
					return;
				}
				if (result.equals("Элемент расписания успешно добавлен")) {
					updateTable();
				}else{
					JOptionPane
					.showMessageDialog(TTEManagementPanel.this,
							result);
				}

			}
		});
		result.add(addTrain);
		return result;
	}

	public void updateTable() {

		timeTableElementsTable.updateTable(ClientEmployee.getInstance()
				.viewTimeTableElements());
	}
}
